library(readxl)
library(sjmisc)
library(moments)
library(corrr)
library(broom)
library(tidyverse)
library(sjlabelled)
library(texreg)
library(xtable)
library(haven)
library(lmtest)
library(grid)
library(gridExtra)
library(foreign)
library(readstata13)
library(writexl)

ruta <- "C:/Users/Matias/Dropbox/Proyectos/Fondecyt Participacion Electoral/Articulos/Electoral Winners y Plebiscito/Harvard Dataverse/2. Constitutional Plebiscite (study 2)/"
#ruta <- "C:/Users/aigon/Dropbox/Fondecyt Participacion Electoral/Encuesta Plebiscito 2022/3_Datos/"

ola_1 <- read_dta(paste0(ruta,"2. Database/Wave1_Study2.dta"))
ola_2 <- read_dta(paste0(ruta,"2. Database/Wave2_Study2.dta"))

get.meta<- function(base) {
  tabla <- tibble("Nombre"= names(base),
                  "Etiqueta de la variable"=as.character(sapply(names(base),function(var){attr(getElement(base,var),"label")})),
                  "Clase"= as.character(sapply(names(base), function(var){class(getElement(base,var))})),
                  "Etiquetas de los valores"= as.character(sapply(names(base),function(var){attr(getElement(base,var),"labels")})),
                  "Valores distintos"=as.numeric(sapply(names(base), function(var){n_distinct(getElement(base,var))})))
  return(tabla)
}

meta.ola_1 <- get.meta(ola_1)
meta.ola_2 <- get.meta(ola_2)

meta.ola_1$Ola <- 1
meta.ola_2$Ola <- 2

meta.olas <- rbind(meta.ola_1,meta.ola_2)

write_xlsx(meta.olas,paste0(ruta,"mapa de varaibles.xlsx"))

# Pasar a numéricas

ola_1 <- ola_1 %>% mutate_at(vars(names(ola_1),
                                  -meta.ola_1$Nombre[meta.ola_1$Clase == "character" | 
                                                       meta.ola_1$Clase == "Date"]),
                             as.numeric) %>% 
  rename(educ = C3, ingreso = C4, n_hogar = C6)

ola_2 <- ola_2 %>% mutate_at(vars(names(ola_2),
                                  -meta.ola_2$Nombre[meta.ola_2$Clase=="character"|
                                                       meta.ola_2$Clase=="Date"]),
                             as.numeric) %>% 
  rename(educ = C1, ingreso = C2, id = ID_Olas) %>% mutate(id = as.numeric(id))

save(ola_1, file = 
       paste0(ruta,"2. Database/ola_1.Rdata"))

save(ola_2, file = 
       paste0(ruta,"2. Database/ola_2.Rdata"))
